package com.ipzoe.common.captcha;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.ipzoe.common.exception.CustomException;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 验证码管理类
 * 
 * @author Eric
 * @date 2019/12/02
 */
@Slf4j
public class CaptchaCodeManager {

    /**
     * 验证码存取工具
     */
    @Setter
    private CaptchaCodeRepository captchaCodeRepository;

    /**
     * 验证码生成器
     */
    @Setter
    private CaptchaCodeGenerator captchaCodeGenerator;

    public CaptchaCode create(String key) {
        Assert.notBlank(key);

        CaptchaCode code = captchaCodeGenerator.generate();
        captchaCodeRepository.save(key, code);

        log.debug("将验证码存入session时的验证码为 {}", code);
        return code;
    }

    public void validate(String key, String codeInRequest) {
        Assert.notBlank(key);
        Assert.notBlank(codeInRequest);

        CaptchaCode codeInSession = captchaCodeRepository.get(key);
        log.info("从session中获取到验证码为 {}", codeInSession);

        if (codeInSession == null) {
            throw new CustomException(400, "验证码不存在");
        }

        if (codeInSession.isExpired()) {
            captchaCodeRepository.remove(key);
            throw new CustomException(400, "验证码已过期");
        }

        if (!StrUtil.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) {
            throw new CustomException(400, "验证码不匹配");
        }
        
        //移除验证码
        captchaCodeRepository.remove(key);

    }

}
